#!/usr/bin/env node

/**
 * Admin账号初始化脚本
 * 用于解决admin登录失败的问题
 * 
 * 使用方法：
 * 1. 在云函数控制台执行此脚本
 * 2. 或者通过API调用 admin/init 接口
 */

const AdminModel = require('../project/model/admin_model.js');
const timeUtil = require('../framework/utils/time_util.js');

async function initAdminAccount() {
    try {
        console.log('=== Admin账号初始化开始 ===');
        
        // 检查是否已存在admin账号
        const existingAdmin = await AdminModel.getOne({}, 'ADMIN_ID,ADMIN_NAME,ADMIN_STATUS');
        
        if (existingAdmin) {
            console.log('✅ Admin账号已存在:', {
                id: existingAdmin.ADMIN_ID,
                name: existingAdmin.ADMIN_NAME,
                status: existingAdmin.ADMIN_STATUS
            });
            
            // 如果admin状态不是启用，则更新状态
            if (existingAdmin.ADMIN_STATUS !== 1) {
                console.log('🔄 更新admin账号状态为启用...');
                await AdminModel.edit(
                    { ADMIN_ID: existingAdmin.ADMIN_ID },
                    { ADMIN_STATUS: 1 }
                );
                console.log('✅ Admin账号状态已更新为启用');
            } else {
                console.log('✅ Admin账号状态正常');
            }
            
            return {
                success: true,
                message: 'Admin账号已存在且状态正常',
                adminId: existingAdmin.ADMIN_ID
            };
        }
        
        // 创建新的admin账号
        console.log('🆕 创建新的admin账号...');
        const adminData = {
            ADMIN_NAME: 'admin',
            ADMIN_PHONE: '13900000000',
            ADMIN_STATUS: 1, // 启用状态
            ADMIN_TYPE: 1,   // 超级管理员
            ADMIN_LOGIN_CNT: 0,
            ADMIN_LOGIN_TIME: 0,
            ADMIN_TOKEN: '',
            ADMIN_TOKEN_TIME: 0,
            ADMIN_ADD_TIME: timeUtil.time(),
            ADMIN_EDIT_TIME: timeUtil.time()
        };
        
        const result = await AdminModel.insert(adminData);
        
        console.log('✅ Admin账号创建成功:', {
            id: result.id,
            name: adminData.ADMIN_NAME,
            status: adminData.ADMIN_STATUS
        });
        
        console.log('=== Admin账号初始化完成 ===');
        
        return {
            success: true,
            message: 'Admin账号创建成功',
            adminId: result.id
        };
        
    } catch (error) {
        console.error('❌ 初始化admin账号失败:', error);
        return {
            success: false,
            message: '初始化admin账号失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    initAdminAccount().then(result => {
        console.log('最终结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { initAdminAccount };
